<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import {
  ElSelect,
  ElOption,
  ElTable,
  ElTableColumn,
  ElPagination,
  ElButton,
  ElUpload,
  ElForm,
  ElFormItem,
  ElDatePicker,
  ElMessage,
  ElCheckbox
} from 'element-plus'
import type { UploadInstance, UploadProps, UploadRawFile } from 'element-plus'
import { Dialog } from '@/components/Dialog'
import { useIcon } from '@/hooks/web/useIcon'
import { RetrieveVariety } from '@/api/sysmanage/variety'
import {
  RetrieveResearchFile,
  RetrieveDeparementWorkFileList,
  CopyDepartmentWorkFile,
  UpdateResearchFile
} from '@/api/syscontent/researchFile'
import { researchFileDataType, ResearchFileType } from './types/researchFile'
import { formatToDate, parseIntegerTime } from '@/utils/dateUtil'
import {
  CopyFileItemType,
  copyFileDiagType,
  updateFileDiagType,
  updateFileItemType
} from './types/researchFile'
import networkConfig from '@/config/network'
const { baseURL } = networkConfig
const uploadRef = ref<UploadInstance>()
const copyFileTable = ref<InstanceType<typeof ElTable>>()
const plusIcon = useIcon({ icon: 'system-uicons:plus' })
const copyIcon = useIcon({ icon: 'mingcute:copy-line' })
const varietyList = ref<Array<{ code: string; name: string }>>()
const fileTypeList = ref<Array<{ name: string; key: string }>>([
  { name: '技术解盘', key: 'TECHNICAL' },
  { name: '晨会纪要', key: 'EARLY' },
  { name: '收盘日评', key: 'DAILY' },
  { name: '每周一报', key: 'WEEKLY' },
  { name: '每月研报', key: 'MONTHLY' },
  { name: '年度报告', key: 'ANNUAL' },
  { name: '其他', key: 'OTHERS' }
])
const fileData = reactive<researchFileDataType>({
  fileType: '',
  page: 1,
  page_size: 50,
  totalCount: 0,
  fileList: []
})

const createFileDiag = reactive({
  isShow: false,
  actionUrl: baseURL + '/v1/admin/dailymaintain/periodReport/researchFile/upload/',
  file_varieties: [],
  uploading: false,
  extraData: {
    varieties: '',
    file_type: '',
    file_date: formatToDate(new Date())
  }
})

const copyFileDiag = reactive<copyFileDiagType>({
  isShow: false,
  dataLoading: false,
  queryDate: formatToDate(new Date()),
  fileList: [],
  copyLoading: false
})

const updateFileDiag = reactive<updateFileDiagType>({
  isShow: false,
  updateLoading: false
})
const editFileItem = reactive<updateFileItemType>({
  rid: -1,
  title: '',
  file_date: '',
  variety_en: '',
  filepath: '',
  is_active: false
})

const toConfirmEditFile = () => {
  updateFileDiag.updateLoading = true
  UpdateResearchFile([editFileItem]).then((res) => {
    ElMessage.success(res.message)
    updateFileDiag.isShow = false
    updateFileDiag.updateLoading = false
    loadFileList()
  })
}

const toCreateFile = () => {
  createFileDiag.isShow = true
}
const handleUploadExceed: UploadProps['onExceed'] = (files) => {
  uploadRef.value!.clearFiles()
  const file = files[0] as UploadRawFile
  file.uid = new Date().getTime()
  uploadRef.value!.handleStart(file)
}
const submitUpload = () => {
  createFileDiag.uploading = true
  createFileDiag.extraData.varieties = createFileDiag.file_varieties.join(',')
  uploadRef.value!.submit()
}
const uploadSuccess = (res: any) => {
  uploadRef.value!.clearFiles()
  ElMessage.success(res.message)
  createFileDiag.isShow = false
  createFileDiag.uploading = false
  loadFileList()
}

const toEditFileRow = (row: ResearchFileType) => {
  Object.assign(editFileItem, row)
  editFileItem.rid = row.id
  updateFileDiag.isShow = true
}

const fileTypeSelectChange = () => {
  fileData.page = 1
  loadFileList()
}

const fileListPageChange = (p: number) => {
  fileData.page = p
  loadFileList()
}
const copyDiagDateChange = (dt: string) => {
  copyFileDiag.queryDate = dt
  loadExistFile()
}

const toCopyFile = () => {
  copyFileDiag.fileList = []
  copyFileDiag.isShow = true
  loadExistFile()
}
const toConfirmCopyFile = () => {
  const selectRows = copyFileTable.value!.getSelectionRows()
  if (!selectRows || selectRows.length < 1) {
    ElMessage.error('请选择条目后再添加!')
    return
  }
  copyFileDiag.copyLoading = true
  const saveList: Array<CopyFileItemType> = selectRows.map((r: CopyFileItemType) => {
    return {
      variety_en: r.variety_en,
      file_date: r.file_date,
      title: r.title,
      file_type: r.file_type,
      filepath: r.filepath
    }
  })
  CopyDepartmentWorkFile(saveList).then((res) => {
    ElMessage.success(res.message)
    const selectIds = selectRows.map((i: any) => i.id)
    const leaveFiles: Array<CopyFileItemType> = []
    for (let i = 0; i < copyFileDiag.fileList.length; i++) {
      const fo: CopyFileItemType = copyFileDiag.fileList[i]
      if (selectIds.indexOf(fo.id) === -1) {
        leaveFiles.push(fo)
      }
    }
    copyFileDiag.fileList = leaveFiles
    copyFileDiag.copyLoading = false
  })
}

const loadFileList = () => {
  RetrieveResearchFile({
    ft: fileData.fileType,
    page: fileData.page,
    page_size: fileData.page_size
  }).then((res) => {
    fileData.fileList = res.data.rows
    fileData.totalCount = res.data.total_count
  })
}

const loadExistFile = () => {
  copyFileDiag.dataLoading = true
  RetrieveDeparementWorkFileList(copyFileDiag.queryDate).then((res) => {
    copyFileDiag.fileList = res.data.files.map((item: any) => {
      return {
        id: item.id,
        file_date: parseIntegerTime(item.file_date),
        file_type: item.file_type,
        title: item.title,
        variety_en: item.variety_en,
        filepath: item.filepath
      }
    })
    copyFileDiag.dataLoading = false
  })
}

onMounted(() => {
  loadFileList()
  RetrieveVariety({ kw: '', scope: 'S01', code: '' }).then((res) => {
    varietyList.value = res.data.data
  })
})
</script>
<template>
  <div class="page-view">
    <div class="actions-bar">
      <ElSelect
        v-model="fileData.fileType"
        clearable
        placeholder="选择报告类型"
        @change="fileTypeSelectChange"
      >
        <ElOption v-for="ft in fileTypeList" :key="ft.key" :value="ft.key" :label="ft.name" />
      </ElSelect>
      <div class="right">
        <ElButton type="primary" :icon="plusIcon" @click="toCreateFile">新增</ElButton>
        <ElButton type="success" :icon="copyIcon" @click="toCopyFile">复制已有</ElButton>
      </div>
    </div>
    <ElTable border stripe style="margin-top: 10px" :data="fileData.fileList">
      <ElTableColumn prop="id" label="ID" width="110">
        <template #default="scope">
          <div class="edit-column" @click="toEditFileRow(scope.row)">
            <Icon class="edit-icon" icon="svg-icon:box-edit" />
            <div class="row-id">{{ scope.row.id }}</div>
          </div>
        </template>
      </ElTableColumn>
      <ElTableColumn prop="file_date" label="日期" width="120" />
      <ElTableColumn prop="title" label="名称">
        <template #default="scope">
          <a target="_blank" :href="scope.row.file_url">{{ scope.row.title }}</a>
        </template>
      </ElTableColumn>
      <ElTableColumn prop="file_type" label="类型" width="110" />
      <ElTableColumn prop="variety_en" label="品种" width="90" />
      <ElTableColumn prop="reading" label="点击量" width="70" />
      <ElTableColumn label="有效" width="70" align="center">
        <template #default="scope">
          <Icon v-if="scope.row.is_active" icon="svg-icon:dash-yes" />
        </template>
      </ElTableColumn>
    </ElTable>
    <ElPagination
      v-model:current-page="fileData.page"
      v-model:page-size="fileData.page_size"
      background
      small
      layout="total,prev,pager,next,jumper"
      style="margin-top: 10px"
      :total="fileData.totalCount"
      @current-change="fileListPageChange"
    />
    <Dialog v-model="createFileDiag.isShow" title="新增研报">
      <ElForm>
        <ElFormItem label="日期">
          <ElDatePicker
            v-model="createFileDiag.extraData.file_date"
            style="width: 100%"
            value-format="YYYY-MM-DD"
          />
        </ElFormItem>
        <ElFormItem label="类型">
          <ElSelect
            v-model="createFileDiag.extraData.file_type"
            style="width: 100%"
            placeholder="请选择报告类型"
          >
            <ElOption v-for="ft in fileTypeList" :key="ft.key" :value="ft.key" :label="ft.name" />
          </ElSelect>
        </ElFormItem>
        <ElFormItem label="品种">
          <ElSelect
            v-model="createFileDiag.file_varieties"
            style="width: 100%"
            filterable
            multiple
            placeholder="请选择报告涉及的品种"
          >
            <ElOption
              v-for="v in varietyList"
              :key="v.code"
              :value="v.code"
              :label="`${v.name} (${v.code})`"
            />
          </ElSelect>
        </ElFormItem>
        <ElFormItem label="文件">
          <ElUpload
            ref="uploadRef"
            accept="*.pdf"
            :limit="1"
            :on-exceed="handleUploadExceed"
            :on-success="uploadSuccess"
            :action="createFileDiag.actionUrl"
            :auto-upload="false"
            :data="createFileDiag.extraData"
          >
            <template #trigger>
              <ElButton>选择文件</ElButton>
            </template>
          </ElUpload>
        </ElFormItem>
      </ElForm>
      <template #footer>
        <ElButton @click="createFileDiag.isShow = false">取消</ElButton>
        <ElButton type="primary" @click="submitUpload">确定上传</ElButton>
      </template>
    </Dialog>
    <Dialog v-model="copyFileDiag.isShow" title="复制现有报告">
      <div v-loading="copyFileDiag.dataLoading">
        <ElDatePicker
          v-model="copyFileDiag.queryDate"
          value-format="YYYY-MM-DD"
          size="small"
          @change="copyDiagDateChange"
        />
        <ElTable
          ref="copyFileTable"
          border
          stripe
          size="small"
          style="margin-top: 5px"
          :data="copyFileDiag.fileList"
        >
          <ElTableColumn type="selection" />
          <ElTableColumn prop="id" label="ID" width="80" />
          <ElTableColumn prop="file_date" label="日期" width="100" />
          <ElTableColumn prop="title" label="名称" />
          <ElTableColumn prop="filepath" label="路径" width="150" show-overflow-tooltip />
          <ElTableColumn prop="variety_en" label="品种" width="100" />
        </ElTable>
      </div>
      <template #footer>
        <ElButton @click="copyFileDiag.isShow = false">取消</ElButton>
        <ElButton type="primary" @click="toConfirmCopyFile">确定复制</ElButton>
      </template>
    </Dialog>
    <Dialog v-model="updateFileDiag.isShow" title="编辑报告">
      <ElForm>
        <ElFormItem label="日期">
          <div>{{ editFileItem.file_date }}</div>
        </ElFormItem>
        <ElFormItem label="名称">
          <div>{{ editFileItem.title }}</div>
        </ElFormItem>
        <ElFormItem label="品种">
          <div>{{ editFileItem.variety_en }}</div>
        </ElFormItem>
        <ElFormItem label="路径">
          <div>{{ editFileItem.filepath }}</div>
        </ElFormItem>
        <ElFormItem label="有效">
          <ElCheckbox v-model="editFileItem.is_active">是</ElCheckbox>
        </ElFormItem>
      </ElForm>
      <template #footer>
        <ElButton @click="updateFileDiag.isShow = false">取消</ElButton>
        <ElButton type="primary" @click="toConfirmEditFile" :loading="updateFileDiag.updateLoading"
          >确定保存</ElButton
        >
      </template>
    </Dialog>
  </div>
</template>
<style scoped lang="less">
.page-view {
  .actions-bar {
    display: flex;
    align-items: center;
    .right {
      margin-left: auto;
      display: flex;
      align-items: center;
    }
  }
  .edit-column {
    display: flex;
    align-items: center;
    cursor: pointer;
    .edit-icon {
      margin-right: 5px;
    }
  }
}
</style>
